<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>打鼓</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <div class="container">
      <div class="box-list">
        <div class="box" data-key="A">A</div>
        <div class="box" data-key="B">B</div>
        <div class="box" data-key="C">C</div>
        <div class="box" data-key="D">D</div>
        <div class="box" data-key="E">E</div>
        <div class="box" data-key="F">F</div>
        <div class="box" data-key="G">G</div>
        <div class="box" data-key="H">H</div>
        <div class="box" data-key="I">I</div>
      </div>
      <audio id="myaudio"></audio>
    </div>
    <div class="hint">
      <p>打开声音，按下键盘，模拟打鼓~！</p>
    </div>
    <script>
      const musicBox = {
        A: "boom.wav",
        B: "clap.wav",
        C: "hihat.wav",
        D: "kick.wav",
        E: "openhat.wav",
        F: "ride.wav",
        G: "snare.wav",
        H: "tink.wav",
        I: "tom.wav",
      };
      const keybox = ["A", "B", "C", "D", "E", "F", "G", "H", "I"];
      const boxList = document.getElementsByClassName("box-list")[0];
      //用事件委托来监听按键
      window.addEventListener("keydown", (event) => {
        if (!keybox.includes(event.key.toUpperCase())) return;
        const key = event.key.toUpperCase();
        const target = document.querySelector(`div[data-key=${key}]`);
        dealwithDom(target);
        dealwithAudio(key);
      });
      function dealwithDom(dom) {
        const target = dom;
        //改变目标元素的样式
        target.className = "box active";
        //过一会再把样式改回来
        setTimeout(() => {
          target.className = "box";
        }, 300);
      }
      function dealwithAudio(key) {
        //获取audio元素
        const myaudio = document.getElementById("myaudio");
        //根据key拼接出audio的src
        myaudio.src = "./sounds/" + musicBox[key];
        //播放audio
        myaudio.play();
      }
    </script>
  </body>
</html>
